package com.lucky.carcodepro.interceptor;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson2.JSON;
import com.lucky.carcodepro.common.annotation.RepeatSubmit;
import com.lucky.carcodepro.domain.response.Response;
import com.lucky.carcodepro.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * RepeatSubmitInterceptor
 * <p>
 * 描述：防重复提交拦截器
 *
 * @author Annie
 * @version 2024/10/7 15:44
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (handler instanceof HandlerMethod handlerMethod) // 使用 instanceof 模式匹配 >>> JDK16
        {
            RepeatSubmit annotation = handlerMethod.getMethod().getAnnotation(RepeatSubmit.class);
            if (ObjUtil.isNotNull(annotation))
            {
                if (this.isRepeatSubmit(request, annotation))
                {
                    Response<String> stringResponse = Response.success(annotation.message());
                    ServletUtils.renderString(response, JSON.toJSONString(stringResponse));
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @return
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);

}
